<script>
import { defineComponent, ref, onMounted } from '@vue/composition-api';
import { Getmaterials, addFile, downloadImgs } from '@/api/organ/groupOrgan';
import { Message, MessageBox } from 'element-ui';
import { getToken } from '@/utils/auth';
import axios from 'axios';

export default defineComponent({
  props: {
    id: String,
  },
  setup(props) {
    const loading = ref(false);
    const open = ref(false);
    const list = ref([]);
    const profileName = ref('');
    const pageNum = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    const uploadUrl = ref('');
    const files = ref('')
    const uploadHeaders = ref({ Authorization: 'Bearer ' + getToken() });
    const upload = ref(
      {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/common/upload',
        // url: process.env.VUE_APP_BASE_API + '/system/user/importData',
        college: '',
        fileChangeFlag: false,
        fileList: [],
        teamid: '',
        progressFlag: true, // 显示进度条
        loadProgress: 0,
      }
    )
    const formRef = ref();
    const formModel = ref({ stuId: '' });

    const loadData = async () => {
      loading.value = true;
      const payload = {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        id: props.id,//'0T8ofpRjLWN9UcwQUO8'//
      };
      const response = await Getmaterials(payload);
      loading.value = false;
      if (response.code === 200) {
        const { rows, total: rowTotal } = response;
        list.value = rows;
        total.value = rowTotal;
      } else {
        loading.value = false;
      }
    };
    // 上传材料
    const AddList = async () => {
      // if (upload.value)
      //   upload.value.clearFiles();
      console.log(upload.value);
      profileName.value = '';
      open.value = true;
      uploadUrl.value = process.env.VUE_APP_BASE_API + '/common/upload'
    }
    // 文件上传中处理
    const handleFileUploadProgress = (event, file, fileList) => {
      upload.value.isUploading = true;
    }
    // 文件上传成功处理
    const handleFileSuccess = (response, file, fileList) => {
      console.log(response, "url");
      if (response.code == 200) {
        files.value = response.url
        upload.value.isUploading = false;
      } else {
        upload.value.clearFiles();
        files.value = null;
        Message({
          message: '上传失败, 请重试',
          type: 'error',
        });
      }
      // upload.value.clearFiles();
    }
    const handleUploadRemove = () => {
      upload.value.clearFiles();
      files.value = null;
    };
    // 上传失败
    const handleUploadError = async (err) => {
      Message({
        message: '上传失败, 请重试',
        type: 'error',
      });
    }
    const resets = async () => {
      upload.value.clearFiles();
      open.value = false
    }
    const submitFileForm = async () => {
      const data = {
        file: files.value,
        profileName: profileName.value,
        id: props.id
      }
      console.log(data, "data")
      if (data.file && data.profileName) {
        // console.log(data);
        const res = await addFile(data)
        console.log(res);
        if (res.code === 200) {
          Message({
            message: '上传成功',
            type: 'success',
          });
          resets()
          loadData()
        }
      } else {
        Message({
          message: '材料信息请填写完整！',
          type: 'error',
        });
      }
    }

    // 下载材料
    const upUrl = async (row) => {

      // console.log(row);
      // window.open(row.url);
      axios(row.url, {
        responseType: 'blob', //重要代码
      }).then(res => {
        const url = window.URL.createObjectURL(new Blob([res.data]));
        const link = document.createElement('a');
        link.href = url;
        var ext = row.url.substring(row.url.lastIndexOf("."))
        let fileName = row.profileName + ext; //保存到本地的文件名称
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
      })
    }
    const goBack = async () => {
      //删除当前标签页
      const detailPath = await handleActivePath(route, true)
      store.dispatch('tabs/delVisitedRoute', detailPath)
      //打开父标签
      await router.push('Transfer')
    };
    const refresh = () => {
      pageNum.value = 1;
      loadData();
    };

    const reset = formEl => {
      formEl.resetFields();
      refresh();
    };

    onMounted(() => {
      loadData();
    });
    return {
      formRef,
      formModel,
      loadData,
      reset,
      loading,
      list,
      total,
      pageNum,
      pageSize,
      AddList,
      upUrl,
      open,
      upload,
      uploadUrl,
      profileName,
      handleFileUploadProgress,
      handleFileSuccess,
      handleUploadRemove,
      handleUploadError,
      submitFileForm,
      uploadHeaders,
      resets
    };
  },
});
</script>

<template>
  <div>
    <el-row>
      <el-form ref="formRef" :model="formModel" inline size="mini">
        <!-- <el-form-item label="学生" prop="stuId">
          <el-input v-model="formModel.stuId" placeholder="请输入学号或姓名" />
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" size="mini" @click="AddList">上传材料</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <el-row>
      <el-table v-loading="loading" :data="list" border>
        <el-table-column label="材料名称" align="center" prop="profileName" />
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="upUrl(scope.row)">
              下载材料
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="pageNum" :limit.sync="pageSize" @pagination="loadData" />
    </el-row>
    <el-dialog title="上传材料" :visible.sync="open" width="400px">

      <el-form ref="form">
        <el-form-item label="材料名称" prop="profileName">
          <el-input v-model="profileName" placeholder="请输入材料名称" />
        </el-form-item>
        <el-form-item>
          <el-upload ref="upload" :limit="1" :action="uploadUrl" :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess" :on-error="handleUploadError" :on-remove="handleUploadRemove"
            :headers="uploadHeaders">
            <el-button size="small" type="primary">材料上传</el-button>
            <div slot="tip" class="el-upload__tip">
              材料一次性最多只能上传1个,材料总大小不能超过1GB
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="resets">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
